package com.kfm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

    private static final List<String> ALLOWED_PATHS = List.of(
            "/",
            "/login",
            "/register",
            "/register.jsp",
            "/captcha"
    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取上下文路径
        String contextPath = request.getContextPath();
        // 获取请求路径
        String requestURI = request.getRequestURI();

        // 去掉上下文路径
        String path = requestURI.replaceFirst(contextPath, "");

        // 过滤请求，如果是静态资源，放行
        if (path.startsWith("/static")) {
            filterChain.doFilter(request, servletResponse);
            return;
        }

        // 如果是登录页面或其他不需要登录的页面，放行
        if (ALLOWED_PATHS.contains(path)) {
            filterChain.doFilter(request, servletResponse);
            return;
        }

        // 是否登录
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            // 未登录，重定向到登录页面
            response.sendRedirect("login");
        } else{
            // 已登录，放行
            filterChain.doFilter(request, servletResponse);
        }

    }
}
